package org.elephas.persistence;

import org.elephas.persistence.query.QueryParam;
import org.elephas.persistence.query.Sort;
import org.hibernate.Query;

/**
 * Base implementation of the {@link Dao} inteface. This class should implement
 * any methods explictly declared in the {@link Dao}
 * 
 * @author ivaynberg
 * 
 */
public abstract class AbstractDao extends AbstractSessionAdapter implements Dao {
	
	public Query createQuery(String hql, QueryParam param) {
		if (param != null) {
			hql = appendSortInfo(hql, param.getSort());
		}
		Query query = createQuery(hql);
		if (param != null) {
			query.setFirstResult(param.getFirst());
			query.setMaxResults(param.getCount());
		}
		return query;
	}

	private String appendSortInfo(String hql, Sort[] sorts) {
		if (sorts == null || sorts.length == 0) {
			return hql;
		}
		StringBuilder sb = new StringBuilder(hql);
		sb.append(" order by ");
		for (int i = 0; i < sorts.length; i++) {
			Sort sort = sorts[i];
			sb.append(sort.getData());
			sb.append(sort.isAscending() ? " asc" : " desc");
			if (i != sorts.length - 1) {
				sb.append(",");
			}
		}
		return sb.toString();
	}

}
